package com.duan.nowcoder.community.controller;

import com.duan.nowcoder.community.entity.Event;
import com.duan.nowcoder.community.entity.User;
import com.duan.nowcoder.community.event.EventProducer;
import com.duan.nowcoder.community.service.LikeService;
import com.duan.nowcoder.community.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/like")
    @ResponseBody
    public String like(int entityType, int entityId, int entityUserId, int postId) {
        User user = hostHolder.getUser();
        //点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);
        //数量
        Long likeCount = likeService.findEntityLikeCount(entityType, entityId);
        //状态
        int state = likeService.isEntityLike(user.getId(), entityType, entityId);
        //返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("likeState", state);
        if (state == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setEntityId(entityId)
                    .setEntityType(entityType)
                    .setUserId(user.getId())
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }
        //加入Redis重算帖子分数
        if (entityId == ENTITY_TYPE_POST) {
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisUtil.sSet(redisKey, postId);
        }
        return CommunityUtil.getJSONString(0, null, map);
    }
}
